<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
		<title>监控地图</title>
		<link rel="stylesheet" href="https://lib.baomitu.com/font-awesome/4.7.0/css/font-awesome.min.css">
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}

			#container {
				position: relative;
			}

			.amap-info-content {
				color: #FFFFFF;
				font-size: 14px;
				background: #FFC010 !important;
				border-radius: 8px;
				text-align: left;
				padding: 4px !important;
			}

			.amap-info-sharp {
				border-top-color: #FFC010 !important;
			}

			.amap-info-close {
				display: none !important;
			}

			.main {
				/* flex-direction: row; */
				color: #FFFFFF;
				font-size: 13px;
				/* justify-content: space-around; */
				/* align-items: center; */
				width: 80px;
				height: 30px;
				line-height: 30px;
				text-align: center;
				background-color: #5677fc;
				/* transition-duration: .28s; */
				/* transition-timing-function: ease-out; */
				/* transition-property: width, background-color; */
				border-bottom-left-radius: 15px;
				border-top-left-radius: 15px;
			}

			.positions {
				position: absolute;
				top: 25px;
				right: 0;
			}

			.positions1 {
				position: absolute;
				top: 75px;
				right: 0;
			}

			.positions2 {
				position: absolute;
				top: 125px;
				right: 0;
			}

			.positions3 {
				position: absolute;
				top: 175px;
				right: 0;
			}

			#carDetail {
				position: fixed;
				right: 0;
				bottom: 20px;
				left: 0;
				background: #FFFFFF;
				border-radius: 4px;
				margin: 0 5px;
				margin-left: 8px;
				margin-right: 8px;
				display: none;
			}

			#detail_main {
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: start;
				/* padding: 5px; */
			}

			.detail_location {
				display: block;
				font-size: 12px;
				width: 300px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}

			#allBtn {
				display: flex;
				flex-direction: row;
				margin-top: 4px;
				flex: 1;
			}

			.btn {
				flex-direction: row;
				flex: 1;
				border-top-width: 1px;
				border-top-style: solid;
				border-top-color: #eaeef1;
				justify-content: center;
				align-items: center;
				text-align: center;
				font-size: 13px;
				color: #777777;
				height: 40px;
				line-height: 40px;
			}

			#tag {
				display: flex;
				flex-direction: row;
			}

			.uni-tag {
				padding: 3px 8px;
				height: 15px;
				line-height: 15px;
				justify-content: center;
				border-radius: 3px;
				border-width: 0.5px;
				border-style: solid;
				font-size: 12px;
			}

			.drawer {
				position: fixed;
				top: 0;
				right: 0;
				bottom: 0;
				left: 0;
				z-index: 1000;
				display: none;
			}

			.drawer__mask {
				/* opacity: 0; */
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background-color: rgba(0, 0, 0, 0.4);
				/* transition: opacity 0.3s; */
			}

			.drawer__content {
				position: absolute;
				top: 0;
				right: 0;
				width: 230px;
				bottom: 0;
				background-color: #ffffff;
				transition: transform 0.3s ease;
				overflow: auto;
			}

			.list-item {
				display: flex;
				flex: 1;
				flex-direction: row;
				align-items: center;
				overflow: hidden;
				border-top-color: #eaeef1;
				border-top-style: solid;
				border-top-width: 0.5px;
				justify-content: space-between;
			}

			#heade-title {
				display: flex;
				flex: 1;
				/* width: 145px; */
				flex-direction: column;
				overflow: hidden;
			}

			.title {
				display: flex;
				flex: 1;
				font-size: 14px;
				color: #3b4144;
				overflow: hidden;
				white-space: nowrap;
			}

			.note {
				display: flex;
				flex: 1;
				margin-top: 3px;
				color: #777777;
				font-size: 12px;
				overflow: hidden;
			}

			#one {
				position: fixed;
				top: 20px;
				height: 100px;
				width: 100%;
				background: #FFFFFF;
			}

			.amap-marker-label {
				border-radius: 4px;
				padding: 0;
				border: none;
				/* border-color: #FFFFFF; */
			}

			#lable {
				background-image: url(./chepai.png);
				border-color: #FFBF05;
				background-size: 100% 100%;
				background-repeat: no-repeat;
				padding: 4px;
				color: black;
				border-radius: 4px;
				background-color: #FFBF05 !important;
			}

			#lable1 {
				color: #FFFFFF;
				background-image: url(./chepai2.png);
				border-color: #cac8c3;
				border-radius: 4px;
				background-size: 100% 100%;
				background-repeat: no-repeat;
				padding: 4px;
				background-color: #cac8c3 !important;
			}

			#Tips {
				position: absolute;
				top: -60px;
				right: 0;
				left: 0;
				bottom: 0;
				margin: auto;
				height: 40px;
				width: 200px;
				border-radius: 5px;
				padding: 10px;
				background-color: rgba(0, 0, 0, .75);
				font-size: 14px;
				color: #FFFFFF;
				display: none;
				z-index: 99999;
			}

			.amap-copyright,
			.amap-logo {
				display: none !important;
			}
		</style>
	</head>
	<body>
		<!-- 地图 -->
		<div id="container"></div>
		<!-- 功能按钮	 -->
		<div>
			<div class="main positions" id="switchMap">卫星地图</div>
			<div class="main positions1" id="traffic">显示路况</div>
			<div class="main positions2" id="showTruckNo">显示车牌</div>
			<div class="main positions3" style="background: #ff7900;" id="checkCar">选择车辆</div>
		</div>

		<!-- 车辆详情 -->
		<div id="carDetail"></div>
		<!--  前置安装提醒-->
		<div id="Tips">
			该车辆为前置安装，无法拨打电话联系车主~
		</div>

		<!-- 选择车辆 -->
		<div id="modle_drawer" class="drawer">
			<div id="mask" class="drawer__mask"></div>
			<div id="content" class="drawer__content"></div>
		</div>


		<!-- uni 的 SDK -->
		<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js">
		</script>
		<script type="text/javascript" src='https://webapi.amap.com/maps?v=1.4.15&key=b5af6d525e8796f797ccad004b6aa444'>
		</script>
		<script type="text/javascript" src="https://lib.baomitu.com/jquery/1.12.4/jquery.min.js">
		</script>
		<script type="text/javascript">
			var carList = []
			var locationData = []; // 经纬度数据
			var status = ''; // 对应sytle样式
			var style = []; //样式序列数组
			var truckList = new Map();
			var curTruck = null; //所选车辆信息
			var curTruckId = null
			var removeList = []
			var list = []
			var truckSelectList = [] //选择车辆数据
			var marker = ""
			var mass = null
			var calloutContent = null
			var infoWindow = null
			var map = null
			var first = true
			var showTruckNo = false

			var layers = []
			var layer1 = new AMap.TileLayer.Satellite();
			var layer2 = new AMap.TileLayer.RoadNet();

			//  tag  颜色  light
			var success = {
				"color": "#19be6b",
				"background-color": "#d7f0db",
				"border-color": "#d7f0db"
			}
			var error = {
				"color": "#ed3f14",
				"background-color": "#fadbd9",
				"border-color": "#fadbd9"
			}
			var primary = {
				"color": "#5677fc",
				"background-color": "#c7eaff",
				"border-color": "#c7eaff"
			}
			var warning = {
				"color": "#ff7900",
				"background-color": "#fde6d2",
				"border-color": "#fde6d2"
			}
			var defaults = {
				"color": "#333",
				"background-color": "#fafafa",
				"border-color": "#fafafa"
			}
			var gray = {
				"color": "#999",
				"background-color": "#ededed",
				"border-color": "#ededed"
			}


			/*
			ApiUrl ---  接口环境
			Token  ---  认证
			*/
			// var ApiUrl = "http://119.27.163.76:9013"; // - 测试
			var ApiUrl = "https://gateway.xbtruck.com/lk-truck-webfront"; // - 正式


			var info = {
				type: 1,
				token: '',
				truckId: ""
			}

			var info = JSON.parse(GetQueryString("info")) ? JSON.parse(GetQueryString("info")) : info
			// 页面初始化请求数据
			function initDate() {
				$.ajax({
					url: ApiUrl + "/truck/getAllTruckLocation",
					dataType: "json",
					type: "POST",
					data: {
						installType: info.type
					},
					headers: {
						"Authorization": info.token
					},
					success: function(res) {
						if (res.data.length) {
							carList = JSON.stringify(res.data)
							handleDatas(carList);
						} else {
							$("#showTruckNo").hide();
							$("#checkCar").hide()
						}
					},
					error: function(err) {
						$("#showTruckNo").hide();
						$("#checkCar").hide()
					}
				})
			}

			var zoom = 3
			var center = [104.065735, 30.659462]
			var TimeEvent = null

			if (first) {
				map = new AMap.Map('container', {
					zoom: zoom,
					showIndoorMap: false,
					resizeEnable: true,
				});
				first = false

				if (info.truckId) {
					curTruckId = Number(info.truckId)
					zoom = 19
					map.setZoom(zoom, false);
					if (TimeEvent) {
						TimeEvent = null
					}
					initDate();
					updateTask();
				}
			}

			function logMapinfo() {
				zoom = map.getZoom(); //获取当前地图级别
			}

			function logMapinfos() {
				center = [map.getCenter().lng, map.getCenter().lat]
			}

			//  处理数据

			var second = true //判断是否初始化显示车牌
			function handleDatas(res) {
				map = new AMap.Map('container', {
					zoom: zoom,
					showIndoorMap: false,
					resizeEnable: true,
				});

				map.on('zoomend', logMapinfo);
				map.on('moveend', logMapinfos);
				map.setCenter(center)
				list = JSON.parse(res) ? JSON.parse(res) : [];
				const arr = []

				if (list.length <= 50 && second) {
					showTruckNo = true;
					second = false
					$('#showTruckNo').text('隐藏车牌')
				}

				list.forEach(x => {
					arr.push(x)
					truckList.set(x.id, x)
				})


				if (layers.length) {
					layers.forEach(item => {
						if (item.CLASS_NAME == 'AMap.TileLayer.Satellite') {
							map.add([layer1]);
						}
						if (item.CLASS_NAME == 'AMap.TileLayer.RoadNet') {
							map.add([layer2]);
						}
					})
				}
				// 按车牌号码排序
				arr.sort((a1, a2) => {
					if (a1.truckNo > a2.truckNo) {
						return 1
					} else {
						return -1
					}
				})
				truckSelectList = arr

				locationData = []
				style = []
				for (var i = 0; i < list.length; i++) {
					// 设置样式
					let obj = {}
					if (curTruck && curTruckId === list[i].id) {
						obj = {
							url: './truck_select.png',
							anchor: new AMap.Pixel(6, 20),
							size: new AMap.Size(18, 40),
							rotation: list[i].gpsInfo.direction,
							id: list[i].id,
							isOnline: list[i].isOnline
						}
					} else {
						if (list[i].isOnline) {
							obj = {
								url: './truck_active.png',
								anchor: new AMap.Pixel(6, 20),
								size: new AMap.Size(18, 40),
								rotation: list[i].gpsInfo.direction,
								id: list[i].id,
								isOnline: list[i].isOnline
							}
						} else {
							obj = {
								url: './truck.png',
								anchor: new AMap.Pixel(6, 20),
								size: new AMap.Size(18, 40),
								rotation: list[i].gpsInfo.direction,
								id: list[i].id,
								isOnline: list[i].isOnline
							}
						}
					}

					style.push(obj)
					var location = [list[i].gpsInfo.lonLat.longitude, list[i].gpsInfo.lonLat.latitude]
					
					locationData.push({
						lnglat: location,
						list: list[i],
						style: i
					})
					console.log(location);
				}
				
				mass = new AMap.MassMarks(locationData, {
					opacity: 1,
					zIndex: 111,
					cursor: 'pointer',
					style: style,
				});

				mass.setMap(map);
				//   marker 点
				if (showTruckNo) {
					for (let i = 0; i < list.length; i++) {

						if (list[i].id === curTruckId) {
							marker = new AMap.Marker({
								position: [list[i].gpsInfo.lonLat.longitude, list[i].gpsInfo.lonLat.latitude],
								content: ' ',
								map: map,
								label: {},
							});
						} else {
							marker = new AMap.Marker({
								position: [list[i].gpsInfo.lonLat.longitude, list[i].gpsInfo.lonLat.latitude],
								content: ' ',
								map: map,
								label: {
									content: list[i].preSale ? (list[i].isOnline ?
										`<div id='lable'>${list[i].truckFrameNo}</div>` :
										`<div id='lable1'>${list[i].truckFrameNo}</div>`) : (
										list[i].isOnline ?
										`<div id='lable'>${list[i].truckNo.substring(0, 2) + "·" + list[i].truckNo.substring(2)}</div>` :
										`<div id='lable1'>${list[i].truckNo.substring(0, 2) + "·" + list[i].truckNo.substring(2)}</div>`
									),
									offset: new AMap.Pixel(-25, -8),
								},
							});
						}
					}
				}
				if (zoom < 8 && curTruckId) {
					curTruckId = null
					curTruck = null
					infoWindow.close()
					$("#carDetail").hide()
					mass.getStyle().forEach((item, index) => {
						item.url = item.isOnline ? "./truck_active.png" : "./truck.png"
					})
					if (TimeEvent) {
						clearInterval(TimeEvent);
						TimeEvent = null
					}
				}

				// 如果带车辆id参数
				if (curTruckId) {
					curTruck = truckList.get(curTruckId);
					massClick(curTruck);
					map.setCenter([curTruck.gpsInfo.lonLat.longitude, curTruck.gpsInfo.lonLat.latitude]);
					infoWindow.open(map, [curTruck.gpsInfo.lonLat.longitude, curTruck.gpsInfo.lonLat.latitude]);
					mass.getStyle().forEach((item, index) => {
						if (item.id === curTruckId && curTruckId) {
							item.url = "./truck_select.png"
						} else {
							item.url = item.isOnline ? "./truck_active.png" : "./truck.png"
						}
					})
				}

				// marker 点击事件
				mass.on('click', function(e) {
					// showTruckNo = false
					initDate();
					if (TimeEvent) {
						clearInterval(TimeEvent);
						TimeEvent = null
					}
					updateTask();
					// 更新位置
					curTruckId = e.data.list.id
					curTruck = truckList.get(Number(curTruckId)) // 车辆信息
					var lnglat = [curTruck.gpsInfo.lonLat.longitude, curTruck.gpsInfo.lonLat.latitude]
					massClick(curTruck);
					infoWindow.open(map, lnglat);
					map.setCenter(lnglat);
					zoom = 19
					map.setZoom(zoom, false);
				});
			}


			function massClick(curTruck) {
				map.setZoom(zoom, false);
				// console.log("选择的车辆信息", curTruck)
				var lnglat = [curTruck.gpsInfo.lonLat.longitude, curTruck.gpsInfo.lonLat.latitude]
				calloutContent = curTruck.truckNo ? curTruck.truckNo : curTruck.truckFrameNo
				// 熄火
				if (!curTruck.isOnline) {
					calloutContent += `</br>熄火${curTruck.onlineTime}`
				} else { //运行
					if (curTruck.gpsInfo.speed) {
						calloutContent += `</br>车速${curTruck.gpsInfo.speed}km/h`
					}
					if (curTruck.gpsInfo.height) {
						calloutContent += `</br>海拔${curTruck.gpsInfo.height}m`
					}
				}
				// 构建信息窗体
				infoWindow = new AMap.InfoWindow({
					content: curTruck ? calloutContent : '',
					offset: new AMap.Pixel(-3, -20),
					autoMove: true,
				});



				// 改变当前marker的样式
				mass.getStyle().forEach((item, index) => {
					if (item.id === curTruckId && curTruckId) {
						item.url = "./truck_select.png"
					} else {
						item.url = item.isOnline ? "./truck_active.png" : "./truck.png"
					}
				})

				// 打开车辆详情
				if (curTruck && $("#carDetail").is(":hidden")) {
					$("#carDetail").show()
				}


				$("#carDetail").empty();
				div =
					`
				<div id="detail_main">
					<div style="width: 60px;margin-left:4px">
						<img id="carImg" src="./truck_active.png" style="width: 60px; height: 60px;">
					</div>
					<div >
						<div style="font-size: 14px;margin-top: 6px;">
							<span>${curTruck.truckNo?curTruck.truckNo:curTruck.truckFrameNo}</span>
							<span>【${curTruck.name?curTruck.name:"前装"}】</span>
						</div>
						<div style="font-size: 12px;color: #777777;margin-top:6px;">
							<span>${curTruck.brandName?curTruck.brandName:''} |</span>
							<span>${curTruck.engineName?curTruck.engineName:''} |</span>
							<span>${curTruck.mali} 匹 </span>
						</div>
						<div style="margin-top:6px; margin-bottom: 6px;  ">
							<span class="detail_location">${curTruck.location}</span>
						</div>
						<div id="tag" style="margin-top:6px; margin-bottom: 6px;  ">
						</div>
					</div>
				</div>
				<div id="allBtn" >
					<div class="btn" id="makePhoneCall">
						<i class="fa fa-phone" aria-hidden="true" ></i>
						<span>联系车主</span>
					</div>
					<div class="btn" id="navigateToPage" style="border-left-width: 1px;  border-left-style: solid;  border-left-color: #eaeef1;">
						<i class="fa fa-wrench" aria-hidden="true"></i>
						<span>进入诊断</span>
					</div>
				</div>
				`
				$("#carDetail").append(div);


				$("#carImg ").attr("src", curTruck.brandImageUrl);



				if (curTruck.marks.length <= 4) {
					curTruck.marks.forEach((item, index) => {
						$("#tag").append(
							`<div id="${index}" class="uni-tag" style="margin-right: 8px;">${item.content}</div>`
						)
						if (item.color === "success") {
							$(`#${index}`).css(success)
						}
						if (item.color === "error") {
							$(`#${index}`).css(error)
						}
						if (item.color === "primary") {
							$(`#${index}`).css(primary)
						}
						if (item.color === "warning") {
							$(`#${index}`).css(warning)
						}
						if (item.color === "default") {
							$(`#${index}`).css(defaults)
						}
					})
				} else {
					curTruck.marks.slice(0, 3).forEach((item, index) => {
						$("#tag").append(
							`<div id="${index}" class="uni-tag" style="margin-right: 8px;">${item.content}</div>`
						)
						if (item.color === "success") {
							$(`#${index}`).css(success)
						}
						if (item.color === "error") {
							$(`#${index}`).css(error)
						}
						if (item.color === "primary") {
							$(`#${index}`).css(primary)
						}
						if (item.color === "warning") {
							$(`#${index}`).css(warning)
						}
						if (item.color === "default") {
							$(`#${index}`).css(defaults)
						}
					})
					curTruck.marks.slice(3).forEach((item, index) => {
						$("#tag").append(
							`<div id="${index}" class="uni-tag" style="margin-right: 8px;">${item.content}</div>`
						)
						if (item.color === "success") {
							$(`#${index}`).css(success)
						}
						if (item.color === "error") {
							$(`#${index}`).css(error)
						}
						if (item.color === "primary") {
							$(`#${index}`).css(primary)
						}
						if (item.color === "warning") {
							$(`#${index}`).css(warning)
						}
						if (item.color === "default") {
							$(`#${index}`).css(defaults)
						}
					})
				}

			}

			function checkCars() {
				var i = 50

				truckSelectList.forEach((item, index) => {
					var lists =
						`
					<ul>
						<li class="list-item" id="${item.id}">
							<div id="heade-title" style="padding:12px;">
								<div class="title">${item.truckNo?item.truckNo:item.truckFrameNo}【${item.name?item.name:'前装'}】</div>
								<div class="note">${item.city}</div>
							</div>
							<div style="margin-right:12px" >
								<div class="uni-tag" id="${i}" style="border-radius: 15px;margin-left: 8px;">${item.isOnline?'运行':'熄火'}</div>
							</div>
						</li>
					</ul>
					`

					$("#content").append(lists);

					if (item.isOnline) {
						$(`#${[i]}`).css(success);
					} else {
						$(`#${[i]}`).css(gray);
					}

					$(`#${item.id}`).click(function() {
						$("#modle_drawer").hide();
						// showTruckNo = false
						// 更新位置
						initDate();
						if (TimeEvent) {
							clearInterval(TimeEvent);
							TimeEvent = null
						}
						updateTask();
						curTruck = item
						curTruckId = item.id
						var lnglat = [curTruck.gpsInfo.lonLat.longitude, curTruck.gpsInfo.lonLat.latitude]
						map.setCenter(lnglat);
						zoom = 19
						map.setZoom(zoom, false);
						massClick(curTruck);
						infoWindow.open(map, lnglat);
					})

					i++
				})
			}


			//选择车辆  打开抽屉
			$("#checkCar").click(function() {
				$("#modle_drawer").show()
				$("#content").empty();
				checkCars();
			})
			//点击遮罩层关闭抽屉
			$("#mask").click(function() {
				$("#modle_drawer").hide()
			})

			// 功能按钮点击事件
			$("#switchMap").click(function() {
				let text = $('#switchMap').text()
				if (text === '卫星地图') {
					layers.push(layer1)
					$('#switchMap').text('普通地图')
					map.add(layers);
				} else {
					map.remove(layer1);
					for (let i = 0; i < layers.length; i++) {
						if (layers[i].CLASS_NAME === 'AMap.TileLayer.Satellite') {
							layers.splice(i, 1)
						}
					}
					$('#switchMap').text('卫星地图')
				}
			});

			$("#traffic").click(function() {
				let text = $('#traffic').text()
				if (text === '显示路况') {
					layers.push(layer2)
					$('#traffic').text('隐藏路况')
					map.add(layers);
				} else {
					map.remove(layer2);

					for (let i = 0; i < layers.length; i++) {
						if (layers[i].CLASS_NAME === 'AMap.TileLayer.RoadNet') {
							layers.splice(i, 1)
						}
					}
					$('#traffic').text('显示路况')
				}

			});


			$("#showTruckNo").click(function() {
				let text = $('#showTruckNo').text()
				if (text === '显示车牌') {
					showTruckNo = true
					$('#showTruckNo').text('隐藏车牌')
				} else {
					showTruckNo = false
					$('#showTruckNo').text('显示车牌')
				}
				initDate();
			});



			document.addEventListener('UniAppJSBridgeReady', function() {

				// 联系车主
				$("#carDetail").on('click', '#makePhoneCall', function(e) {
					console.log(curTruck)
					if (curTruck.preSale) {
						$("#Tips").show()
						setTimeout(function() {
							$("#Tips").hide()
						}, 2000)
					} else {
						uni.postMessage({
							data: {
								action: "telephone", // pageTo（页面跳转）telephone（拨打电话）
								data: curTruck.mobile
							}
						});
					}

				})

				//  进入诊断
				$("#carDetail").on('click', '#navigateToPage', function(e) {
					uni.postMessage({
						data: {
							action: "navigateTo", // pageTo（页面跳转）telephone（拨打电话）
							data: {
								equipNo: curTruck.equipNo,
								truckNo: curTruck.truckNo,
								pageType: 1,
								subUrl: "/#/"
							}
						}
					});
				})
			});


			//定时刷新位置 
			function updateTask() {
				// 1分钟刷新一次数据
				TimeEvent = setInterval(() => {
					initDate();
				}, 5 * 1000)
			}




			// 获取url参数
			function GetQueryString(name) {
				var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				var r = location.search.substr(1).match(reg);
				if (r != null) return unescape(r[2]);
				return null;
			}


			// 页面初始加载
			$(window).load(function() {
				// 初始化加载数据
				initDate();
				checkCars();
				logMapinfo();
				// 动态设置地图宽高
				$("#container").width(document.documentElement.clientWidth).height(document.documentElement
					.clientHeight);
			});
		</script>
	</body>
</html>
